<template>
  <div class="user-management-container">
    <el-card class="management-card">
      <template #header>
        <div class="card-header">
          <h2>用户管理</h2>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加用户
          </el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户名或邮箱"
              @input="handleSearch"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select v-model="statusFilter" placeholder="状态筛选" @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="活跃" value="active" />
              <el-option label="禁用" value="disabled" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="roleFilter" placeholder="角色筛选" @change="handleFilter">
              <el-option label="全部角色" value="" />
              <el-option label="管理员" value="admin" />
              <el-option label="普通用户" value="user" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button @click="resetFilters">重置筛选</el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 用户列表表格 -->
      <el-table
        :data="filteredUsers"
        style="width: 100%"
        v-loading="loading"
        stripe
        border
        height="500"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <el-tag :type="getRoleType(scope.row.role)">
              {{ getRoleText(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLogin" label="最后登录" width="160" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="editUser(scope.row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              :type="scope.row.status === 'active' ? 'warning' : 'success'"
              size="small"
              @click="toggleUserStatus(scope.row)"
            >
              <el-icon><Switch /></el-icon>
              {{ scope.row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteUser(scope.row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑用户' : '添加用户'"
      width="600px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio label="active">活跃</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Edit, Switch, Delete } from '@element-plus/icons-vue'

// 用户数据类型
interface User {
  id: number
  username: string
  email: string
  role: 'admin' | 'user'
  status: 'active' | 'disabled'
  lastLogin: string
  createTime: string
}

// 响应式数据
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')
const statusFilter = ref('')
const roleFilter = ref('')

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const userFormRef = ref()

// 用户表单
const userForm = reactive({
  id: 0,
  username: '',
  email: '',
  role: 'user' as 'admin' | 'user',
  status: 'active' as 'active' | 'disabled'
})

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 模拟用户数据
const allUsers = ref<User[]>([])

// 生成模拟数据
const generateMockUsers = (): User[] => {
  const users: User[] = []
  const roles: ('admin' | 'user')[] = ['admin', 'user']
  const statuses: ('active' | 'disabled')[] = ['active', 'disabled']
  const usernames = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十', '郑十一', '王十二']
  
  for (let i = 1; i <= 50; i++) {
    const randomRole = roles[Math.floor(Math.random() * roles.length)]
    const randomStatus = statuses[Math.floor(Math.random() * statuses.length)]
    const randomUsername = usernames[Math.floor(Math.random() * usernames.length)]
    
    users.push({
      id: i,
      username: `${randomUsername}${i}`,
      email: `user${i}@example.com`,
      role: randomRole,
      status: randomStatus,
      lastLogin: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toLocaleString(),
      createTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toLocaleString()
    })
  }
  
  return users
}

// 计算属性 - 过滤后的用户列表
const filteredUsers = computed(() => {
  let filtered = allUsers.value
  
  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(user => 
      user.username.toLowerCase().includes(keyword) ||
      user.email.toLowerCase().includes(keyword)
    )
  }
  
  // 状态过滤
  if (statusFilter.value) {
    filtered = filtered.filter(user => user.status === statusFilter.value)
  }
  
  // 角色过滤
  if (roleFilter.value) {
    filtered = filtered.filter(user => user.role === roleFilter.value)
  }
  
  total.value = filtered.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

// 获取角色类型
const getRoleType = (role: string) => {
  return role === 'admin' ? 'danger' : 'primary'
}

// 获取角色文本
const getRoleText = (role: string) => {
  return role === 'admin' ? '管理员' : '普通用户'
}

// 获取状态类型
const getStatusType = (status: string) => {
  return status === 'active' ? 'success' : 'warning'
}

// 获取状态文本
const getStatusText = (status: string) => {
  return status === 'active' ? '活跃' : '禁用'
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 筛选处理
const handleFilter = () => {
  currentPage.value = 1
}

// 重置筛选
const resetFilters = () => {
  searchKeyword.value = ''
  statusFilter.value = ''
  roleFilter.value = ''
  currentPage.value = 1
}

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  resetUserForm()
  dialogVisible.value = true
}

// 编辑用户
const editUser = (user: User) => {
  isEdit.value = true
  userForm.id = user.id
  userForm.username = user.username
  userForm.email = user.email
  userForm.role = user.role
  userForm.status = user.status
  dialogVisible.value = true
}

// 重置用户表单
const resetUserForm = () => {
  userForm.id = 0
  userForm.username = ''
  userForm.email = ''
  userForm.role = 'user'
  userForm.status = 'active'
}

// 保存用户
const saveUser = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    
    if (isEdit.value) {
      // 编辑用户
      const index = allUsers.value.findIndex(user => user.id === userForm.id)
      if (index !== -1) {
        allUsers.value[index] = {
          ...allUsers.value[index],
          username: userForm.username,
          email: userForm.email,
          role: userForm.role,
          status: userForm.status
        }
      }
      ElMessage.success('用户更新成功！')
    } else {
      // 添加用户
      const newUser: User = {
        id: Math.max(...allUsers.value.map(u => u.id)) + 1,
        username: userForm.username,
        email: userForm.email,
        role: userForm.role,
        status: userForm.status,
        lastLogin: '从未登录',
        createTime: new Date().toLocaleString()
      }
      allUsers.value.unshift(newUser)
      ElMessage.success('用户添加成功！')
    }
    
    dialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 切换用户状态
const toggleUserStatus = async (user: User) => {
  const action = user.status === 'active' ? '禁用' : '启用'
  
  try {
    await ElMessageBox.confirm(`确定要${action}用户 "${user.username}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    user.status = user.status === 'active' ? 'disabled' : 'active'
    ElMessage.success(`用户${action}成功！`)
  } catch {
    // 用户取消操作
  }
}

// 删除用户
const deleteUser = async (user: User) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 "${user.username}" 吗？此操作不可恢复！`, '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    })
    
    const index = allUsers.value.findIndex(u => u.id === user.id)
    if (index !== -1) {
      allUsers.value.splice(index, 1)
      ElMessage.success('用户删除成功！')
    }
  } catch {
    // 用户取消操作
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 组件挂载时初始化数据
onMounted(() => {
  allUsers.value = generateMockUsers()
  total.value = allUsers.value.length
})
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}

.management-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #333;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}
</style>
